// 债券
import React from 'react';
import { connect } from 'dva';
import { TableC, SecondHeaderC, TradingClassif, NoQueryC, PrimaryGhostC } from '../../../comps';
import { message, Tabs } from 'antd';
import exchangecodeConfig from '../../../comps/business/tradingMarket/config';
import { exportFile } from '../../../utils/commonFunc';
import Resolution from './resolution';
import Behavior from './behaviorTable';
const { TabPane } = Tabs;
class BondC extends React.Component {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };
  state = {
    informationCurrentPage: 1, // 信息表表格页码
    informationPageSize: 10, // 信息表格每页展示条数
    informationPageInfo: { currentPage: 1, numInPage: 10, total: 0 }, // 信息表格展示底部分页数据
    accountCurrentPage: 1, // 流水表表格页码
    accountPageSize: 10, // 流水表格每页展示条数
    accountPageInfo: { currentPage: 1, numInPage: 10, total: 0 }, // 流水表格展示底部分页数据
    informationColumns: [], // 信息表表格列
    informationDataSource: [], // 信息表格数据
    accountColumns: [], // 流水表表格列
    accountDataSource: [], // 流水表格数据
    isReset: false, // 是否重置
    informationQueryItems: {}, // 信息表查询数据
    accountQueryItems: '', // 流水表查询数据
    visible: false, // 模态框
    tradeInfo: {}, // 模态框数据
    isEdit: false, // 模态框判断是否详情
    isDouble: false, // 是否双击数据
    resolutionType: '1', // 是否拆分 0-未拆分 1-已拆分
    settlementType: '1', // 是否交收 0-未交收 1-已交收
    rowData: '', // 双击数据标识
    accountId: '', // 获取流水表id
    settlement: false, // 模态框判断是否交收
    activeKey: '0', // 交易信息默认展示交易表
    isActiveKey: false,
    accountType: 1, // 流水表展示哪个信息表数据 0-交易 1-行为
  };

  //初始化函数
  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // 查询条件变更时查询数据
    if (JSON.stringify(this.props.queryItems) != JSON.stringify(nextProps.queryItems)) {
      // delete nextProps.queryItems.timestamp
      this.getInformationData(nextProps.queryItems);
    }
  }

  //获取信息表格数据
  getInformationData = (queryItems, current, isResolution) => {
    const { informationCurrentPage, informationPageSize } = this.state;
    this.setState({
      // 表格loading
      informationColumns: undefined,
      informationDataSource: undefined,
      informationQueryItems: queryItems, // 更新本组件查询条件
      isDouble: false, //只要重新查新信息表数据，交易表数据也要重新双击数据展示
      isReset: false,
      resolutionType: '1',
      settlementType: '1',
      rowData: '',
    });
    this.props.dispatch({
      type: 'moreFundsOrderM/getBondInformationData',
      payload: {
        ...queryItems,
        securityType: '0',
        userId: localStorage.getItem('antd-pro-userId'),
        currentPage: current ? current : informationCurrentPage,
        numInPage: informationPageSize,
      },
      callback: (data) => {
        if (data) {
          const newColumns = this.informationColumnsChange(data.columns);
          this.setState(
            {
              informationColumns: newColumns,
              informationDataSource: data.dataSource,
              informationPageInfo: data.pageInfo,
            },
            () => {
              if (isResolution) {
                this.setState({ rowData: this.state.tradeInfo.id, isDouble: true, resolutionType: '1', accountId: this.state.tradeInfo.id });
              }
            },
          );
        } else {
          this.setState({
            informationColumns: [],
            informationDataSource: [],
            informationPageInfo: { currentPage: 1, numInPage: 10, total: 0 },
          });
        }
      },
    });
  };

  //获取流水表数据
  getAccountData = (id, index) => {
    const { accountCurrentPage, accountPageSize } = this.state;
    this.setState({
      // 表格loading
      accountColumns: undefined,
      accountDataSource: undefined,
      accountQueryItems: id,
    });
    this.props.dispatch({
      type: 'moreFundsOrderM/getBondAccountData',
      payload: {
        id: id,
        currentPage: accountCurrentPage,
        numInPage: accountPageSize,
        index,
      },
      callback: (data) => {
        if (data) {
          const newColumns = this.accountColumnsChange(data.columns);
          this.setState({
            accountColumns: newColumns,
            accountDataSource: data.dataSource,
            accountPageInfo: data.pageInfo,
          });
        } else {
          this.setState({
            accountColumns: [],
            accountDataSource: [],
            accountPageInfo: { currentPage: 1, numInPage: 10, total: 0 },
          });
        }
      },
    });
  };

  // 信息表数据列优化
  informationColumnsChange = (columns) => {
    columns.map((item) => {
      if (item.key == 'exchangecode') {
        item.render = (val) => {
          let text = exchangecodeConfig.filter((i) => i.value == val);
          if (text && text.length > 0) {
            return text[0].title;
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'direction') {
        item.render = (val) => {
          let text = TradingClassif[1].tradingDirect.filter((i) => i.value == val);
          if (text && text.length > 0) {
            return text[0].title;
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'amount') {
        (item.type = 'number'), (item.toFixed = 2);
      }
      if (item.key == 'price' || item.key == 'fullPrice' || item.key == 'settlementAmount') {
        (item.type = 'money'), (item.toFixed = 4);
      }
      if (item.key == 'fee') {
        (item.type = 'money'), (item.toFixed = 2);
      }
      if (item.key == 'date') {
        item.type = 'date';
      }
      if (item.key == 'settlementSpeed') {
        item.render = (val) => {
          if (val == '1') {
            return 'T+0';
          }
          if (val == '2') {
            return 'T+1';
          }
          if (val == '0') {
            return 'T+0';
          }
        };
      }
      if (item.key == 'resolutionType') {
        item.render = (val) => {
          if (val == '0') {
            return '未拆分';
          }
          if (val == '1') {
            return '已拆分';
          }
        };
      }
      if (item.key == 'instructionStatus') {
        item.render = (val, record) => {
          if (record.resolutionType == '0') {
            return '--';
          } else {
            switch (val) {
              case '6':
                return '未交收';
              case '4':
                return '已交收';
              case '7':
                return '已交收';
              case '8':
                return '到期交收';
              case '11':
                return '到期未交收';
              default:
                return '--';
            }
          }
        };
      }
    });

    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        operates: [
          {
            title: '拆分',
            onClick: (record, index) => {
              this.resolution(record, index);
            },
            rules: {
              hide: { items: [{ key: 'resolutionType', value: ['1'], relation: ['='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.delete(record.id);
            },
            rules: {
              hide: { items: [{ key: 'resolutionType', value: ['1'], relation: ['='] }] },
            },
          },
          {
            title: '交收',
            onClick: (record, index) => {
              this.settlement(record);
            },
            rules: {
              //已交收时隐藏
              hide: {
                items: [
                  { key: 'resolutionType', value: ['0'], relation: ['='] },
                  { key: 'instructionStatus', value: ['4', '7', '8'], relation: ['=', '=', '='] },
                ],
                relation: 'or',
              },
            },
          },
          {
            title: '回退',
            onClick: (record, index) => {
              this.back(record.id);
            },
            rules: {
              //已交收时隐藏
              hide: {
                items: [
                  { key: 'resolutionType', value: ['0'], relation: ['='] },
                  { key: 'instructionStatus', value: ['4', '7', '8'], relation: ['=', '=', '='] },
                ],
                relation: 'or',
              },
            },
          },
          {
            title: '详情',
            onClick: (record, index) => {
              this.detail(record);
            },
            rules: {
              hide: { items: [{ key: 'resolutionType', value: ['0'], relation: ['='] }] },
            },
          },
        ],
      });
    }
    return columns;
  };

  // 流水表数据列优化
  accountColumnsChange = (columns) => {
    columns.map((item) => {
      if (item.key == 'exchangecode') {
        item.render = (val) => {
          let text = exchangecodeConfig.filter((i) => i.value == val);
          if (text && text.length > 0) {
            return text[0].title;
          } else {
            return '--';
          }
        };
      }
      // if (item.key == 'direction') {
      //     item.render = (val) => {
      //         let text = TradingClassif[1].tradingDirect.filter(i => i.value == val)
      //         if (text && text.length > 0) {
      //             return text[0].title
      //         } else {
      //             return '--'
      //         }
      //     }
      // }
      if (item.key == 'dealAmountTotal') {
        (item.type = 'number'), (item.toFixed = 0);
      }
      if (
        item.key == 'parValueTotal' ||
        item.key == 'dealValue' ||
        item.key == 'dealFullPrice' ||
        item.key == 'totalDealValueTotal' ||
        item.key == 'netvaluation' ||
        item.key == 'fullvaluationfinal'
      ) {
        (item.type = 'money'), (item.toFixed = 4);
      }
      if (item.key == 'fee') {
        (item.type = 'money'), (item.toFixed = 2);
      }
      if (item.key == 'dealRate' || item.key == 'exerciseDealRate' || item.key == 'yield' || item.key == 'exerciseYield') {
        item.align = 'right';
        item.render = (text) => {
          if (text === null || text === undefined) {
            return '--';
          } else {
            // NaN: Not a Number
            // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
            if (isNaN(text)) {
              return text;
            } else {
              return Number(text).toFixed(4) + '%';
            }
          }
        };
      }
      if (item.key == 'date' || item.key == 'settlementDay' || item.key == 'nextExercisedt') {
        item.type = 'date';
      }
    });
    return columns;
  };

  //响应重置
  onClear = () => {
    this.setState({ currentPage: 1, pageSize: 10, isReset: true });
    this.state.isActiveKey && this.Behavior.onClear();
  };

  // 响应拆分
  resolution = (record, index) => {
    record.orderType = '0';
    this.setState({
      visible: true,
      tradeInfo: record,
    });
  };

  // 响应详情
  detail = (record) => {
    record.orderType = '0';
    this.setState({
      visible: true,
      tradeInfo: record,
      isEdit: true,
    });
  };

  // 响应交收
  settlement = (record) => {
    record.orderType = '0';
    this.setState({
      visible: true,
      tradeInfo: record,
      settlement: true,
      isEdit: true,
    });
  };

  // 响应删除
  delete = (id) => {
    this.props.dispatch({
      type: 'moreFundsOrderM/deleteData',
      payload: { id: id },
      callback: (data) => {
        if (data) {
          this.getInformationData(this.state.informationQueryItems);
        }
      },
    });
  };

  // 响应回退
  back = (id) => {
    this.props.dispatch({
      type: 'moreFundsOrderM/backData',
      payload: { id: id },
      callback: (data) => {
        if (data) {
          this.getInformationData(this.state.informationQueryItems);
        }
      },
    });
  };

  //信息表分页点击
  informationTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        informationCurrentPage: current,
        informationPageSize: pageSize,
      },
      () => {
        this.getInformationData(this.state.informationQueryItems);
      },
    );
  };

  //流水表分页点击
  accountTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        accountCurrentPage: current,
        accountPageSize: pageSize,
      },
      () => {
        this.getAccountData(this.state.accountQueryItems, this.state.accountType);
      },
    );
  };

  //响应信息表双击事件
  doubleClick = (record, index) => {
    if (record.resolutionType == '0') {
      this.setState({ isDouble: false, resolutionType: '0' });
    } else {
      this.setState({ isDouble: true, resolutionType: '1', accountId: record.id, accountType: 1 });
      this.getAccountData(record.id, 1);
    }
  };

  //行为表双击
  onBehaviorDoubleClick = (record, isSettlement) => {
    if (!isSettlement) {
      // 行为表示交收成功调用还是双击调用
      if (record.instructionStatus == '6' || record.instructionStatus == '11' || record.resolutionType == '0') {
        this.setState({ isDouble: false, settlementType: '0' });
      } else {
        this.setState({ isDouble: true, settlementType: '1', accountId: record.id, accountType: 2 });
        this.getAccountData(record.id, 2);
      }
    } else {
      this.setState({ isDouble: true, settlementType: '1', accountId: record.id });
    }
  };

  //响应模态框确定事件
  onOk = () => {
    this.setState({ visible: false, settlement: false, isEdit: false, accountType: 1 });
    this.getInformationData(this.state.informationQueryItems, false, true);
    this.getAccountData(this.state.tradeInfo.id, 1);
  };
  changeAccountType = () => {
    this.setState({ accountType: 2 });
  };
  //响应模态框取消事件
  onCancel = () => {
    this.setState({ visible: false, settlement: false, isEdit: false });
  };

  // 响应导出
  export = () => {
    let exportData = _.cloneDeep(this.state.informationQueryItems);
    exportData.currentPage = 1;
    exportData.numInPage = 100000;
    exportData.id = this.state.accountId;
    exportData.productGroupId = JSON.stringify(exportData.productGroupId);
    if (this.state.activeKey == '0') {
      exportFile('api/v1/productGroupTradeInstruction/export', exportData);
    } else {
      exportData.type = 0;
      exportFile('api/v1/productGroupTradeInstruction/exportTradeGroup', exportData);
    }
  };
  //teb切换响应
  tebOnchange = (val) => {
    this.setState(
      {
        activeKey: val,
        resolutionType: '1',
        settlementType: '1',
        isDouble: false,
        rowData: '',
        isActiveKey: true,
      },
      () => this.Behavior?.changeRow(),
    );
  };
  render() {
    const {
      informationColumns,
      informationDataSource,
      informationPageInfo,
      accountColumns,
      accountDataSource,
      accountPageInfo,
      visible,
      tradeInfo,
      isEdit,
      isDouble,
      resolutionType,
      rowData,
      settlement,
      activeKey,
      settlementType,
    } = this.state;
    return (
      <div>
        <div className='secoundTabContainer'>
          <SecondHeaderC title='交易信息' />
          <Tabs activeKey={activeKey} defaultActiveKey='0' onChange={this.tebOnchange} size='small'>
            <TabPane tab='交易' key='0'>
              <TableC
                columns={informationColumns}
                dataSource={informationDataSource}
                current={informationPageInfo.currentPage}
                pageSize={informationPageInfo.numInPage}
                total={informationPageInfo.total}
                scroll={{ x: 'max-content' }}
                rowKey='id'
                pagination={true}
                onChange={this.informationTableChange}
                onRow={(record, index) => {
                  return {
                    onDoubleClick: (event) => {
                      //响应onDoubleClick事件
                      this.doubleClick(record);
                      this.setState({
                        rowData: record.id,
                      });
                    },
                  };
                }}
                rowClassName={(record, index) => {
                  return record.id === rowData ? 'trade-select' : '';
                }}
              />
            </TabPane>
            <TabPane tab='行为' key='1'>
              <Behavior
                queryItems={this.state.informationQueryItems}
                getAccountData={this.getAccountData}
                changeAccountType={this.changeAccountType}
                onBehaviorDoubleClick={this.onBehaviorDoubleClick}
                type={'0'}
                onRef={(ref) => (this.Behavior = ref)}
              />
            </TabPane>
          </Tabs>
        </div>
        <div style={{ marginTop: '10px' }}>
          <SecondHeaderC title='流水信息' />
          <div style={{ marginBottom: '10px', textAlign: 'right' }}>
            <PrimaryGhostC title={'导出'} disabled={!isDouble} onClick={this.export} />
          </div>
          {isDouble && (
            <TableC
              columns={accountColumns}
              dataSource={accountDataSource}
              current={accountPageInfo.currentPage}
              pageSize={accountPageInfo.numInPage}
              total={accountPageInfo.total}
              scroll={{ x: 'max-content' }}
              rowKey='id'
              pagination={true}
              onChange={this.accountTableChange}
            />
          )}
          {!isDouble && (
            <NoQueryC
              title={
                (resolutionType == '0' && activeKey == '0') || (settlementType == '0' && activeKey == '1')
                  ? resolutionType == '0' && activeKey == '0'
                    ? '交易还未拆分，请执行拆分'
                    : '还未交收，请执行交收'
                  : '请双击一条交易信息，展示对应的交易流水'
              }
            />
          )}
        </div>
        {visible && <Resolution visible={visible} tradeInfo={tradeInfo} isEdit={isEdit} settlement={settlement} onOk={this.onOk} onCancel={this.onCancel} />}
      </div>
    );
  }
}

export default connect(({ moreFundsOrderM }) => ({ moreFundsOrderM }))(BondC);
